﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Media;
using AtletIS.Shared.Events;

namespace AtletIS.Shared.Helpers
{
    public class FalseStartHelper : IDisposable
    {
        #region Public properties

        public bool IsConnected { get; set; }
        public event EventHandler DataProcessed;

        #endregion

        #region Private fields

        private SerialPort _serialPort;
        private List<KeyValuePair<int, string>> _reactions;

        #endregion

        #region Ctor

        public FalseStartHelper()
        {
            this.Initialize();
        }

        #endregion

        #region Private methods

        private void Initialize()
        {
            this.IsConnected = false;
            
            try
            {
                string portName = string.Format("COM{0}", Globals.FalseStartPort);
                _serialPort = new SerialPort(portName, 9600, Parity.None, 7, StopBits.One);
                _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                _serialPort.Open();

                if (_serialPort.IsOpen)
                    this.IsConnected = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _serialPort = null;
            }
        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;

            try
            {
                // 8 drah = 481 znakov
                if (sp.BytesToRead == 481)
                {
                    SystemSounds.Beep.Play();

                    this._reactions = new List<KeyValuePair<int, string>>();

                    string indata = sp.ReadExisting();
                    string[] lines = indata.Split('\r');

                    if (lines[8].Substring(3, 1) == "1")
                    {
                        #region Nova citacka

                        for (int i = 8; i <= 15; i++)
                        {
                            int nLane = Convert.ToInt32(lines[i].Substring(3, 1));
                            string sReaction = lines[i].Substring(15, 6);

                            this._reactions.Add(new KeyValuePair<int, string>(nLane, sReaction));
                        }

                        #endregion
                    }
                    else
                    {
                        #region Stara citacka

                        for (int i = 4; i <= 11; i++)
                        {
                            int nLane = Convert.ToInt32(lines[i].Substring(3, 1));
                            string sReaction = lines[i].Substring(15, 6);

                            this._reactions.Add(new KeyValuePair<int, string>(nLane, sReaction));
                        }

                        #endregion
                    }

                    // Raises DataProcessed event
                    if (this.DataProcessed != null)
                        this.DataProcessed(this, new FalseStartEventArgs { Reactions = _reactions });
                }
            }
            catch (Exception ex) 
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        #endregion

        #region Public methods

        public void Dispose()
        {
            if (_serialPort != null && _serialPort.IsOpen)
            {
                _serialPort.Close();
                _serialPort.Dispose();
            }
        }

        #endregion


    }
}
